const path = require("path");
const koaBody = require("koa-body");
const static = require("koa-static");
const render = require("koa-art-template");
const router = require("../routers");
const { generateKey } = require("../utils/crypto");
const { env } = require("process");
// const session = require("koa-generic-session");
// const Redis = require("koa-redis");
function initProject(app) {
  app.use(koaBody());
  app.use(router.routes());
  // 视图渲染的中间件
  app.use(static(path.resolve(__dirname, "../../public/static")));
  //使用redis
  // app.use(
  //   session({
  //     key: "nightowl",
  //     prefix: "epidemic",
  //     store: new Redis(),
  //   })
  // );
  render(app, {
    root: path.resolve(__dirname, "../views"),
    extname: ".html",
    debug: process.env.NODE_ENV !== "production",
  });
  //优雅处理404报错和505报错
  app.use(async (ctx, next) => {
    try {
      await next(); // 执行后代的代码
      if (!ctx.body) {
        // 没有资源
        ctx.render("404");
      }
    } catch (e) {
      // 如果后面的代码报错 返回500
      // ctx.render("500");
    }
  });
  env.NODE_ENV == "production" && generateKey(); //生成一套加密的公钥和私钥,生产环境才执行
}
module.exports = initProject;
